/*
 *  utils.c
 *  Angel&Demon
 *
 *  Created by Si-Mohamed Lamraoui on 04/11/10.
 *  Copyright 2010 UJF. All rights reserved.
 *
 */

#include "utils.h"


/**
 *
 */
void blit_int(int number, int x, int y, TTF_Font *font, SDL_Surface *screen) {
	SDL_Color black_color;
	SDL_Surface *text = NULL;
	SDL_Rect pos;
	char buffer[32];
	black_color.r = 0; black_color.g = 0; black_color.b = 0;
	pos.x = x; 
	pos.y = y;
	if(screen==NULL) {
		error("Null pointer", "blit_int");
		return;
	}
	sprintf(buffer, "%d", number);
	text = TTF_RenderText_Blended(font, buffer, black_color);
	if(text==NULL) {
		error("Null pointer", "blit_int");
		return;
	}
	SDL_BlitSurface(text, NULL, screen, &pos);	
}


/**
 *
 */
void blit_text(const char *str, int x, int y, TTF_Font *font, SDL_Surface *screen) {
	SDL_Color black_color;
	SDL_Surface *text = NULL;
	SDL_Rect pos;
	black_color.r = 0; black_color.g = 0; black_color.b = 0;
	pos.x = x; 
	pos.y = y;
	if(screen==NULL) {
		error("Null pointer", "blit_text");
		return;
	}
	text = TTF_RenderText_Blended(font, str, black_color);
	if(text==NULL) {
		error("Null pointer", "blit_text");
		return;
	}
	SDL_BlitSurface(text, NULL, screen, &pos);	
}


/**
 *
 */
void blit_image(SDL_Surface *image, int x, int y, SDL_Surface *screen) {
	SDL_Rect pos;
	pos.x = x; pos.y = y;
	if(image==NULL || screen==NULL) {
		error("Null pointer", "blit_image");
		return;
	}
	SDL_BlitSurface(image, NULL, screen, &pos);
}


/**
 *
 */
void timer_restart(mytimer_t *t) {
#ifdef PSP
	sceKernelLibcGettimeofday(&t->start, NULL);
#else
	gettimeofday(&t->start, NULL);
#endif	
}


/**
 *
 */
int timer_state(mytimer_t *t, int duration) {
#ifdef PSP
	sceKernelLibcGettimeofday(&t->end, NULL);
#else
	gettimeofday(&t->end, NULL);
#endif
	if(((t->end).tv_sec-(t->start).tv_sec)*1000000+((t->end).tv_usec-(t->start).tv_usec)>duration)
		return TRUE;
	else
		return FALSE;
}


/**
 *
 */
SDL_Surface *load_colorkey_image(const char *path) {
	SDL_Surface *image = NULL; 
	image = SDL_LoadBMP(path);	
	if(image==NULL) {
		error("Couldn't load bmp", SDL_GetError());
		return NULL;
	}
	SDL_SetColorKey(image, SDL_SRCCOLORKEY, SDL_MapRGB(image->format, 255, 0, 255));
	return image;
}

/**
 *
 */
SDL_Surface *load_image(const char *path) {
	SDL_Surface *image = NULL; 
	image = SDL_LoadBMP(path);	
	if(image==NULL) {
		error("Couldn't load bmp", SDL_GetError());
		return NULL;
	}
	return image;
}


/*
 *
 */
void error(const char *err, char *arg) {
	printf("%s: %s\n", err, arg);
	FILE *log = fopen("log.txt", "w+");
	if(log!=NULL) {
		fprintf(log, "%s: %s\n", err, arg);
		fclose(log);
	} else {
		printf("log error\n");
	}
	
#ifdef PSP
	SDL_Delay(2000);
#endif
}




